<?php
class BaseCrud extends Controller {
  var $modelname = ''; /* Nome do model sem o "_model" */
  var $base_url = '';
  var $actions = 'CRUD';
  var $acoes_extras = array(); //array("url" => "methodo do controller", "title" => "texto que aparece", "class" => "classe do link")
  var $titulo;
  var $tabela = '';
  var $campos_busca = '';
  var $verificar_login = true;
  var $delete_fields = '';
  var $joins = false;
	var $group = false;
	var $base_ativo = false;

  function BaseCrud () {
    parent::Controller();
    $this->_modelname();
  }

  function _modelname() {
    return $this->modelname.'_model';
  }

  function _model() {
    $model = $this->_modelname();
    $this->load->model($model);
    return $this->$model;
  }

  function _call_pre_form () {
    if (method_exists($this, '_pre_form'))
      $this->_pre_form();
  }

  function _call_pos_form () {
    if (method_exists($this, '_pos_form'))
      $this->_pos_form();
  }

  function _call_filter_pre_form (&$data) {
    if (method_exists($this, '_filter_pre_form'))
      $this->_filter_pre_form($data);
  }

  function _crud() {
    $crud = $this->actions;
    $crud = str_split($crud, 1);
    return $crud;
  }

  function _call_filter_pre_save (&$data) {
    if (method_exists($this, '_filter_pre_save'))
      $this->_filter_pre_save($data);
  }

  function _call_filter_pos_save (&$data) {
    if (method_exists($this, '_filter_pos_save'))
      $this->_filter_pos_save($data);
  }

  function _call_filter_pos_delete () {
    if (method_exists($this, '_filter_pos_delete'))
      $this->_filter_pos_delete();
  }

  function _call_filter_pre_busca(&$data) {
    if (method_exists($this, '_filter_pre_busca'))
      $this->_filter_pre_busca($data);
  }

  function _call_filter_pos_busca(&$data) {
    if (method_exists($this, '_filter_pos_busca'))
      $this->_filter_pos_busca($data);
  }

  function _call_filter_pre_read (&$data) {
    if (method_exists($this, '_filter_pre_read'))
      $this->_filter_pre_read($data);
  }
  
  function _call_filter_pre_listar (&$where) {
    if (method_exists($this, '_filter_pre_listar'))
      $this->_filter_pre_listar($where);
  }

  function _setVal(&$data, $key, $value) {
    $data[0]['values'][$key] = $value;
  }

  function _call_pre_validate($method) {
    if (method_exists($this, '_pre_validate'))
      $this->_pre_validate($method);
  }
  
  function index(){
    $this->listar();
  }

  function listar () {
    if(!$this->session->userdata('admin'))
      redirect('auth/login');

    $this->load->model($this->modelname."_model", 'model');
	
    $config['base_url'] = site_url($this->base_url."/listar/");
    $config['uri_segment'] = 3;
    $config['per_page'] = 100;
		
		$where = array("{$this->model->table}.ativo" =>1);
    $busca = $this->input->posts();
	
    if(!is_numeric($this->uri->segment(3)) and $this->uri->segment(3) != ""){
      $query = base64_decode($this->uri->segment(3));
      $termos = explode("&", $query);
      foreach ($termos as $item) {
        $termo = explode("=", $item);
        if(isset($termo[1]))
          $busca[$termo[0]] = $termo[1];
      }
    }

    if(count($busca) > 0){
      $url = "";
      foreach ($busca as $key => $value) {
        if($value){
          $where[$key] = $value; 
          $this->model->fields[$key]['value'] = $value;
          $url .= $key."=".$value."&";
        }
      }
      $params = url_title(base64_encode($url));
      $config['base_url'] = site_url($this->base_url."/listar/{$params}");
      $config['uri_segment'] = 4;
    }
    $this->_call_filter_pre_listar($where);
    $order = array($this->model->table.".".$this->model->id_col => "desc");
    $results = $this->model->search($where, $this->uri->segment($config['uri_segment']), $config['per_page'], "*", $this->joins,"", $order,$this->group);

    $config['total_rows'] = $results['total_rows'];
    $data['total'] = $results['total_rows'];

    $this->_call_filter_pre_read($results['resultados']);
    $data['itens'] = $results['resultados'];

    $this->load->library('pagination');
    $this->pagination->initialize($config);
    $data['paginacao'] = $this->pagination->create_links();
    
    $data['form']="";
	
    foreach (explode(',', $this->campos_busca) as $item){
	  $this->model->fields[trim($item)]['class'] = str_replace('vObrigatorio', '', $this->model->fields[trim($item)]['class']);
      $data['form'] .= $this->model->form(trim($item));
    }
    $data['titulo'] = $this->titulo;
    $data['url'] = site_url($this->base_url);
    $data['crud'] = $this->_crud();
    $data['acoes_extras'] = $this->acoes_extras;
    $data['campos'] = explode (',', $this->tabela);
    $data['model'] = $this->model;

    $this->load->view( 'header');
    $this->load->view( 'crud/index', $data);
    $this->load->view( 'footer' );
  }

  function _try_save (&$data, $method='novo', $id=null) {
    $c =& $this;
    $model = $this->_model();
    $crud = $this->_crud();
    $url = site_url($this->base_url);

    if ($_POST) {

      foreach (array_keys($model->fields) as $k)
        $data[0]['values'][$k] = $this->input->post($k);

      $this->_call_pre_validate($method);

      if ($model->validar()) {
        $_data = array ();
        foreach (array_keys($model->fields) as $item)
          $_data[$item] = $data[0]['values'][$item];
        if ($id) $_data[$model->id_col] = $id;
        $this->_call_filter_pre_save($_data);
        // Salvando

        $id = $model->save($_data);
        $this->_call_filter_pos_save($_data);
        if (in_array('U', $crud))
          redirect($this->base_url.'/editar/'.$id.'/ok');
        else
          redirect($this->base_url);
      }
    }
  }

  function novo() {
    if(!$this->session->userdata('admin'))
      redirect('auth/login');

    $c =& $this;
    $model = $this->_model();
    $crud = $this->_crud();
    $data = array ();
    $url = site_url($this->base_url);
    $action = '/novo';
    $ok = false;
    $titulo = "Cadastrar";

    $this->_try_save($data);

    $this->load->view('header');
    $this->load->view('crud/form' , compact('ok', 'action', 'titulo', 'url', 'model', 'data', 'c','titulo'));
    $this->load->view('footer');
  }

  function editar($id, $ok=null) {
    if(!$this->session->userdata('admin'))
      redirect('auth/login');

    $c =& $this;
    $model = $this->_model();
    $crud = $this->_crud();
    $url = site_url($this->base_url);
    $action = '/editar/'.$id;
    $titulo = 'Editar';

    $r = $model->get($id)->row();
    if (!$r) die ('<h1>Erro 500</h1><p>Este registro não foi encontrado no banco de dados.</p>');

    $data = array (array('values' => (array) $r));

    $this->_try_save($data, 'update', $id);

    $this->load->view('header');
    $this->load->view('crud/form', compact( 'titulo', 'url', 'model', 'data', 'c', 'action', 'ok', 'crud'));
    $this->load->view('footer');
  }

  function _delete($id) {
    //$this->_model()->delete($id);
		$model = $this->_model();
		$dados = array($model->id_col =>$id, 'ativo' => 0);
		$model->save($dados);
    $this->_call_filter_pos_delete();
  }

  function deletar($id) {
    if(!$this->session->userdata('admin'))
      redirect('auth/login');

    if($this->input->post('ajax')) {
      $this->_delete($id);
      die('ok');
    }
  }

}
